<template>
  <div class="common-layout">
    <el-container class="box">
      <!-- 左侧菜单栏 -->
      <el-aside class="el-aside">
        <h1 class="logoBox">学生信息管理系统</h1>
        <el-menu active-text-color="#ffd04b"
          background-color="#545c64"
          class="el-menu-vertical-demo"
          default-active="2"
          :unique-opened="true"
          text-color="#fff"
          :router="true">
          <template v-for="item in filteredMenu">
            <!-- 两级菜单 -->
            <template v-if="item.subs">
              <el-sub-menu :index="item.title"
                :key="item.title">
                <template #title>
                  <el-icon>
                    <Document />
                  </el-icon>
                  <span>{{ item.title }}</span>
                </template>
                <template v-for="subItem in item.subs"
                  :key="subItem.index">
                  <el-menu-item :index="subItem.index"
                    @click="() => handleMenuItem(subItem)">{{ subItem.title }}</el-menu-item>
                </template>
              </el-sub-menu>
            </template>
            <!-- 一级菜单 -->
            <template v-else>
              <el-menu-item :index="item.index"
                :key="item.title"
                @click="() => handleMenuItem(item)">
                <el-icon>
                  <Document />
                </el-icon>
                <span>{{ item.title }}</span>
              </el-menu-item>
            </template>
          </template>
        </el-menu>
      </el-aside>

      <el-container>
        <!-- header头部菜单 -->
        <el-header class="header">
          <el-menu class="el-menu-demo"
            mode="horizontal"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b">
            <el-menu-item index="1"
              class="fr">你好，{{ displayName }}</el-menu-item>
            <el-sub-menu index="2"
              class="fr">
              <template #title>我的工作台</template>
              <el-menu-item index="2-1">我的消息</el-menu-item>
              <el-menu-item index="2-2">设置</el-menu-item>
              <el-menu-item index="2-3"
                @click="exitLogin">退出登陆</el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-header>

        <!-- 主体模块：标签页 + 当前路由内容 -->
        <el-main class="el-main">
          <el-tabs type="border-card"
            v-model="activeTabName"
            class="demo-tabs"
            @tab-remove="handleRemove"
            @tab-click="handleSwitchRoute">
            <el-tab-pane v-for="item in editableTabs"
              :key="item.index"
              :label="item.title"
              :name="item.index"
              :closable="handleisClose(item)">
              <router-view />
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
} from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { EventBus } from '@/utils/event-bus' // 导入事件总线
import { getUserInfo, setUserInfo } from '@/utils/auth' // 导入本地用户信息工具
import { getAllUser } from "@/api/user" // 导入API方法

export default {
  name: "MainLayout",
  components: {
    Document,
    IconMenu,
    Location,
    Setting,
  },
  data() {
    return {
      activeTabName: "home",
      editableTabs: [
        {
          title: "首页",
          index: "home",
        },
      ],
      // 原始菜单配置
      originalMenu: [
        {
          title: "用户中心",
          index: "user",
        },
        {
          title: "权限管理",
          subs: [
            { title: "角色列表", index: "roles" },
            { title: "权限列表", index: "rights" },
          ],
          // 添加权限配置：仅允许角色1和2访问
          requiredRoles: [1, 2]
        },
        { 
          title: "学院管理", 
          index: "department",
          requiredRoles: [1, 2,3] 
        },
        { 
          title: "专业管理", 
          index: "major",
          requiredRoles: [1, 2,3] 
        },
        {
          title: "教师管理",
          subs: [
            { title: "教师列表", index: "teacher" },
            { title: "班级管理", index: "classs" },
          ],
          requiredRoles: [1,2,3] 
        },
        {
          title: "课程管理",
          subs: [
            { title: "课程管理", index: "courses" },
          ],
          requiredRoles: [1, 2,3] 
        },
        {
          title: "学生管理",
          subs: [
            { title: "学生管理", index: "student" },
          ],
          requiredRoles: [1, 2,3]
        },
      ],
      userInfo: null, // 用户信息状态
      displayName: '未登录',
      isLoadingUserInfo: false, // 加载状态
    };
  },
  created() {
    // 监听路由变化，保存标签页状态
    this.$router.afterEach(() => {
      this.saveTabsState();
    });

    // 监听重置标签页事件
    EventBus.on('reset-tabs', this.resetTabsState)

    // 获取用户信息
    this.fetchUserInfo();
  },
  beforeDestroy() {
    // 移除事件监听
    EventBus.off('reset-tabs', this.resetTabsState)
  },
  mounted() {
    this.restoreTabsState();
    this.syncTabsWithRoute();

    // 从本地存储获取用户信息作为初始值
    const localUserInfo = getUserInfo();
    if (localUserInfo) {
      this.userInfo = localUserInfo;
    }
  },
  computed: {
    // 计算显示的用户名，提供默认值
    displayName() {
      return this.userInfo?.account || this.userInfo?.name || '未登录';
    },
    
    
    // 根据用户角色过滤菜单
    filteredMenu() {
      // 如果没有用户信息，返回空数组
      if (!this.userInfo) return [];
      
      const userRoleId = this.userInfo.roleId;
      
      // 过滤菜单项，只保留有权限的项
      return this.originalMenu.filter(item => {
        // 如果菜单项没有设置requiredRoles，默认所有人可见
        if (!item.requiredRoles) return true;
        
        // 如果设置了requiredRoles，检查用户角色是否在允许列表中
        return item.requiredRoles.includes(userRoleId);
      });
    }
  },
  watch: {
    activeTabName() {
      console.log("高亮的index值", this.activeTabName);
    },
  },
  methods: {
    handleisClose(item) {
      return item.index !== "home";
    },

    // 重置标签页状态
    resetTabsState() {
      this.editableTabs = [
        { title: "首页", index: "home" },
      ];
      this.activeTabName = "home";
      this.saveTabsState();
      console.log('标签页已重置为初始状态');
    },

    // 从本地存储恢复标签页状态
    restoreTabsState() {
      try {
        const savedTabs = localStorage.getItem('editableTabs');
        const savedActiveTab = localStorage.getItem('activeTabName');

        if (savedTabs) {
          this.editableTabs = JSON.parse(savedTabs);
          const activeTabExists = this.editableTabs.some(tab => tab.index === savedActiveTab);
          this.activeTabName = activeTabExists ? savedActiveTab : "home";
        }
      } catch (error) {
        console.error('恢复标签页状态失败:', error);
        this.editableTabs = [{ title: "首页", index: "home" }];
        this.activeTabName = "home";
      }
    },

    // 保存标签页状态到本地存储
    saveTabsState() {
      try {
        localStorage.setItem('editableTabs', JSON.stringify(this.editableTabs));
        localStorage.setItem('activeTabName', this.activeTabName);
      } catch (error) {
        console.error('保存标签页状态失败:', error);
      }
    },

    // 同步标签页与当前路由
    syncTabsWithRoute() {
      const currentRouteName = this.$route.path.replace('/', '');
      if (currentRouteName && currentRouteName !== 'home') {
        const tabExists = this.editableTabs.some(tab => tab.index === currentRouteName);
        if (!tabExists) {
          const menuItem = this.findMenuItemByIndex(currentRouteName);
          if (menuItem) {
            this.editableTabs.push({ title: menuItem.title, index: currentRouteName });
            this.activeTabName = currentRouteName;
            this.saveTabsState();
          }
        } else {
          this.activeTabName = currentRouteName;
        }
      }
    },

    // 从菜单配置中查找菜单项
    findMenuItemByIndex(index) {
      for (const item of this.originalMenu) {
        if (item.index === index) return item;
        if (item.subs) {
          for (const subItem of item.subs) {
            if (subItem.index === index) return subItem;
          }
        }
      }
      return null;
    },

    // 处理菜单项点击
    handleMenuItem(obj) {
      this.activeTabName = obj.index;
      if (!this.editableTabs.some(tab => tab.index === obj.index)) {
        this.editableTabs.push(obj);
        this.saveTabsState();
      }
    },

    // 处理标签页点击
    handleSwitchRoute(tabsPaneContext) {
      const tabPaneName = tabsPaneContext.paneName || 0;
      this.$router.push("/" + (tabPaneName === 0 ? "" : tabPaneName));
      this.saveTabsState();
    },

    // 处理标签页移除
    handleRemove(tabPaneName) {
      const eleIndex = this.editableTabs.findIndex(tab => tab.index === tabPaneName);
      const routeIndex = this.editableTabs[eleIndex - 1]?.index || "home";

      this.activeTabName = routeIndex;
      this.$router.push("/" + routeIndex);
      this.editableTabs.splice(eleIndex, 1);
      this.saveTabsState();
    },

    // 从本地存储和API获取用户信息
    async fetchUserInfo() {
      // 先从本地存储获取用户信息
      const localUserInfo = getUserInfo();
      if (localUserInfo) {
        this.userInfo = localUserInfo;
        console.log('从本地获取用户信息:', this.userInfo);
      }

      // 再尝试从API获取最新用户信息
      // try {
      //   // 从API获取用户信息（直接调用导入的getAllUser函数）
      //   const response = await getAllUser();
      //   if (response.code === 200 && response.data) {
      //     this.userInfo = response.data;
      //     setUserInfo(this.userInfo); // 更新本地存储
      //     console.log('API用户信息:', this.userInfo);
      //   }
      // } catch (error) {
      //   console.error('获取用户信息API失败:', error);
      // }
    },
    // 获取用户信息API
    async getUserInfoAPI() {
      // 假设getUserInfo返回Promise
      return await getAllUser();
    },

    // 退出登录
    async exitLogin() {
      // 退出登录逻辑
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      // 清空用户信息
      this.userInfo = null;
      this.$router.push('/login');
    }
  }
};
</script>

<style scoped>
.logoBox {
  position: absolute;
  top: 18px;
  left: 30px;
  font-size: 24px;
  color: #fff;
}

.box {
  width: 100vw;
  height: 100vh;
}

.header {
  padding: 0;
  height: 58px;
}

.el-menu--horizontal {
  justify-content: flex-end;
}

.el-header .el-menu,
.el-aside .el-menu {
  border: none;
}

.el-main {
  background-color: #e9eef3;
}

.el-aside {
  width: 240px;
  background: #545c64;
  padding-top: 58px;
}

.el-tabs--border-card .el-tabs__content {
  padding: 0;
}

.demo-tabs>.el-tabs__content {
  background-color: transparent;
}
</style>